package com.ruoyi.utils;

import java.io.*;

/**
 * 文件和字节数组转换
 *
 * @author liuliya
 */
public class ByteUtil {

    public static void convertByteArrayToFile(byte[] bytes, String filePath) {
        try (
                BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(bytes));
                FileOutputStream fileOutputStream = new FileOutputStream(filePath);
                BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream)
        ) {
            int data;
            while ((data = bis.read()) != -1) {
                bos.write(data);
            }
            bos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static byte[] convertFileToByteArray(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return new byte[0];
        }
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            int data;
            while ((data = bis.read()) != -1) {
                bos.write(data);
            }
            bos.flush();
            return bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new byte[0];
    }


}
